package ft.ess.impl;

import java.io.IOException;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;

public class EchoSocketServerLoader extends Application
{
	private Stage primaryStage = null;
	EchoSocketServerController ctl = null;
	private static final String FORM_PATH = "ess.fxml";
	private static final String STAGE_TITLE = "Echo Socket Receiver";
	
	@Override
	public void start(Stage primaryStage)
	{
		this.primaryStage = primaryStage;
		initFxml();
	}
	
	private void initFxml()
	{
		Parent form = null;
		FXMLLoader loader = null;
		
		try
		{
			loader = new FXMLLoader(getClass().getResource(FORM_PATH));
			form = loader.load();
		}
		catch(IOException ex)
		{
			System.out.println(ex.getMessage());
		}
		catch(Exception ex)
		{
			System.out.println(ex.getMessage());
		}
		
		if(form!=null)
		{
			Scene scene = new Scene(form);
			
			// 对stage设置按 ESC 键退出
			scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
				public void handle(KeyEvent arg0)
				{
					if( arg0.getCode() == KeyCode.ESCAPE )
					{
						// 退出前停止监听
						if(ctl!=null)
						{
							ctl.stopListening();
						}
						Platform.exit();
					}
				}
			});
			
			primaryStage.setScene(scene);
			primaryStage.setTitle(STAGE_TITLE);
			
			primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>(){
				public void handle(WindowEvent arg0) {
					/// DEBUG /// 测试，使用 KeyCode.ESCAPE 键盘触发的 Platform.exit() 会不会到这里
					// System.out.println("正在退出");
					// 结论，不会触发上述代码执行，程序也没有正常退出。
					// 但是，使用窗口右上角的关闭按钮，上述代码可以正常运行，程序也能正常退出。
					//// DEBUG ////
					
					// 如果监听线程仍在运行，则停止它。
					ctl.stopListening();
				}
			});
			primaryStage.show();
		}
		
		if(loader!=null)
		{
			ctl = loader.getController();
		}
		
	}
}
